package com.app.web.common

import com.app.model.wrapper.JsonResultWrapper
import com.fasterxml.jackson.databind.ObjectMapper
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.commons.fileupload.FileItem
import org.apache.commons.fileupload.FileItemFactory
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
import org.apache.shiro.authz.annotation.RequiresUser
import org.springframework.stereotype.Component

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.ws.rs.POST
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import java.text.SimpleDateFormat

/**
 * Created by chenxu on 2014/8/8.
 */
@Component
@CompileStatic
@TypeChecked
@Path("/file")
class ImportAction {


    @Path("/import")
    @POST
    @RequiresUser
    @Produces(MediaType.APPLICATION_JSON)
    save(@Context HttpServletRequest request,@Context HttpServletResponse response) {

        String result
        ObjectMapper om = new ObjectMapper()
        try {
            //文件保存目录路径
            String savePath = request.getRealPath("/") + "/attached/";
            //文件保存目录URL
            String saveUrl = request.getContextPath() + "/attached/";

            //定义允许上传的文件扩展名
            HashMap<String, String> extMap = new HashMap<String, String>();
            extMap.put("image", "gif,jpg,jpeg,png,bmp");
            extMap.put("flash", "swf,flv");
            extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            long maxSize = 1000000;
            JsonResultWrapper jsonResultWrapper = new JsonResultWrapper("0001", "", "");
            response.setContentType("text/html; charset=UTF-8");

            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception('{"error":"0001","message":"请选择文件"}')
            }
            //检查目录
            File uploadDir = new File(savePath);
            if (!uploadDir.isDirectory()) {
                throw new Exception('{"error":"0002","message: "上传目录不存在"}')
            }
            //检查目录写权限
            if (!uploadDir.canWrite()) {
                throw new Exception('{"error":"0003","message": "上传目录没有写权限"}')
            }

            String dirName = request.getParameter("dir");
            if (dirName == null) {
                dirName = "image";
            }
            if (!extMap.containsKey(dirName)) {
                throw new Exception('{"error":"0003","message": "目录名不正确"}')
            }
            //创建文件夹
            savePath += dirName + "/";
            saveUrl += dirName + "/";
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(new Date());
            savePath += ymd + "/";
            saveUrl += ymd + "/";
            File dirFile = new File(savePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            List items = upload.parseRequest(request);
            Iterator itr = items.iterator();
            List<String> urls = new ArrayList<String>();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                String fileName = item.getName();
                long fileSize = item.getSize();
                println "${item} ${item.isFormField()} ${item.fieldName} ${item.contentType}"
                if (!item.isFormField()) {
                    //检查文件大小
                    if (item.getSize() > maxSize) {
                        throw new Exception('{"error":"0004","message": "上传文件大小超过限制"}');
                    }
                    //检查扩展名
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                        throw new Exception('{"error":"0005","message": "上传文件扩展名是不允许的扩展名。<br>.只允许'+extMap.get(dirName)+'格式。"}');
                        //out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));

                    }

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                    try {
                        File uploadedFile = new File(savePath, newFileName);
                        item.write(uploadedFile);
                    } catch (Exception e) {
                        throw new Exception('{"error":"0006","message": "上传文件失败"}');
                    }
                    urls.add(saveUrl + newFileName);
                }
            }

            result= urls.size() == 0 ? '{"error":"0008","message": "无url"}':('{"error":0, "url":"'+ (urls.size() == 1 ? urls.get(0) :om.writeValueAsString( urls))+'"}') ;

        } catch (Exception e) {
            result=e.message
        }
        println result
        String isAjax= request.getParameter("isAjax");
        if("1".equals(isAjax)){
            result;
        }else{
        PrintWriter out = response.getWriter();
        out.println("<script  type=\"text/javascript\">window.name='" + result + "';</script>");
        out.flush();
        out.close();
        }
        //om.readValue(result,Map.getClass());
    }
}
